package com.bs.resa.service.impl;

import com.bs.resa.common.RedisUtils;
import com.bs.resa.dao.FileMapper;
import com.bs.resa.dao.LogMapper;
import com.bs.resa.dao.ProjectFileMapper;
import com.bs.resa.dao.TaskMapper;
import com.bs.resa.pojo.AdminUser;
import com.bs.resa.pojo.File;
import com.bs.resa.pojo.Log;
import com.bs.resa.pojo.ProjectFile;
import com.bs.resa.service.FileServive;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author lin
 * @date 2019/4/2 17:59
 */
@Service
public class FileServiceImpl implements FileServive {
    private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

    private Log log=new Log();
    @Resource
    ProjectFileMapper projectFileMapper;


    @Resource
    FileMapper fileMapper;
    @Resource
    TaskMapper taskMapper;
    @Resource
    RedisUtils redisUtils;
    @Resource
    LogMapper logMapper;
    /**
     * 为项目新增文件
     *
     * @param pid
     * @param file1
     * @return
     */
    @Override
    public Boolean insertFile(String type,String pid, File file1) {
        boolean flag=false;
        try {
            //新增文件
            int j=0;
            AdminUser adminUser=((AdminUser)redisUtils.getObject("userinfo"));
            /*记录日志相关*/
            log.setUserId(adminUser.getId());
            log.setData(df.parse(df.format(new Date())));


            int i=fileMapper.insertFile(file1);
            log.setFileId(Long.valueOf(file1.getFid()));
            redisUtils.set("fid",String.valueOf(file1.getFid()));
            if(type.equals("project")){
                //新增文件与项目的关联表
                if(i!=0) j = projectFileMapper.insert(pid, file1.getFid());
                log.setProjectId(Long.valueOf(pid));
                log.setDesc("用户"+adminUser.getAccount()+"为项目当前项目新增了附件："+file1.getFtitle());
            }else if(type.equals("task")){
                //新增文件与任务的关联表
                if(i!=0) j = taskMapper.insertFile(redisUtils.get("tid"), file1.getFid());
                log.setDesc("用户"+adminUser.getAccount()+"为任务新增了附件："+file1.getFtitle());
            }
            logMapper.insertLog(log);

            if (j != 0) {
                if (i != 0) flag = true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }


        return flag;
    }



    @Override
    public List<File> queryProjectFiles(String pid) {
        System.out.println("项目文件："+pid);
        return projectFileMapper.queryFileByPid(pid);
    }

    @Override
    public File queryFileById(String fid) {
        return fileMapper.querybyId(Long.valueOf(fid));
    }

    @Override
    public int deleteFileById(String fid) {
        return fileMapper.deleteByFid(fid);
    }


}
